//
//  Login_mes_VC.swift
//  旅航ios
//
//  Created by tulip on 2021/5/17.
//

import UIKit
import Moya
import SwiftyJSON
import HandyJSON
class Login_mes_VC: UIViewController {

    var timer :Timer!
    var leftTime:Int = 60
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    @IBOutlet weak var postBtn: UIButton!
    @IBOutlet weak var messageBtn: UIButton!
    @IBOutlet weak var message: UITextField!
    @IBOutlet weak var phone: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        postBtn=gradientColor(colo1: "ff8e4a", colo2: "ff6635", view: postBtn,width: SCREEN_WIDTH-30) as? UIButton
        postBtn.layer.cornerRadius=6
        postBtn.layer.masksToBounds=true
        
    }


  
    @IBAction func regist(_ sender: Any) {
        let vc=RegistVC.init()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func loginByPwd(_ sender: Any) {
        let vc=Login_PWD_VC.init()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    @IBAction func getMessage(_ sender: Any) {
        if phone.text == "" {
            YProgressHUD.showToast("请输入手机号码")
        }else{
            let dic=["mobile":phone.text ?? "","event":"mobilelogin"] as [String : Any]
            Network.request(.messageCode(dic)) { (JSON) in
                YProgressHUD.showToast(JSON["msg"].string)
                if JSON["code"].int == 1 {
                    self.messageBtn.isEnabled=false
                    self.timer = Timer.scheduledTimer(timeInterval: TimeInterval(1), target: self, selector: #selector(self.tickDown), userInfo: nil, repeats: true)
                }
            } failure: { (err) in
                
            }

            
        }
        
    }
    
    @IBAction func post(_ sender: Any) {
        guard let text = self.phone.text else { return YProgressHUD.showToast("手机号码不能为空") }
        if text.isEmpty {
            YProgressHUD.showToast("手机号码不能为空")
            return
        }
        guard let captcha = self.message.text else { return YProgressHUD.showToast("手机验证码不能为空") }
        if captcha.isEmpty {
            YProgressHUD.showToast("手机验证码不能为空")
            return
        }
        cancelableRequest = NetWorkRequest(API1.mobilelogin(parameters: ["mobile":text,"captcha":captcha]), completion: { (JSON) -> (Void) in
            
            
            if JSON["code"].int == 1 {
                
                let token =  JSON["data"]["userinfo"]["token"].string
                
                if(token == nil){
                    YProgressHUD.showToast("链接错误")
                    return
                }
                UserDefaults.standard.setValue(token, forKey: "token")
                UserDefaults.standard.setValue(true, forKey: "isLogin")
                
                
               
                guard let model = JSONDeserializer<User>.deserializeFrom(json: "\(JSON["data"]["userinfo"])") else {
                    return
                }
                
                print("***\(model.token)")
                
                UserManager.shared.currentUser = model
                UserManager.shared.saveUserinfo()
       
                TOKEN=token ?? ""
                let vc=MTTabBarController.init()
                UIApplication.shared.keyWindow?.rootViewController=vc
               
            }
            
//            let token =  responseString["data"]["userinfo"]["token"].string
//
//
//            if(token == nil){
//                YProgressHUD.showToast("链接错误")
//                return
//            }
//            UserDefaults.standard.setValue(token, forKey: "token")
//            UserDefaults.standard.setValue(true, forKey: "isLogin")
//
//            guard let model = JSONDeserializer<User>.deserializeFrom(json: "\(JSON["data"]["userinfo"])") else {
//                return
//            }
//
//            print("***\(model.token)")
//
//            UserManager.shared.currentUser = model
//            UserManager.shared.saveUserinfo()
//
//
//            TOKEN=token ?? ""
//            let vc=MTTabBarController.init()
//            UIApplication.shared.keyWindow?.rootViewController=vc
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常")
        })
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.navigationBar.isHidden=true
    }
    
    
    @IBAction func back(_ sender: Any) {
        
        self.navigationController?.popViewController(animated: true)
    }
    
    
    @objc func tickDown() {
        
        //将剩余时间减少1秒
        
        leftTime -= 1
        
        print(leftTime)
        
        //修改button的剩余时间

        messageBtn.setTitle(String(leftTime)+"s", for: .normal)
       
        
        //如果剩余时间小于等于0
        
        if leftTime <= 0 {
            
            //取消定时器
            
            timer.invalidate()
            
            messageBtn.isEnabled = true
            messageBtn.setTitle("获取验证码", for: .normal)
            leftTime = 60
        }
        
    }
    
}
